package com.iot.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot.domain.Device;
import com.iot.service.IotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wlr
 * @since 2022-01-05
 */
@RestController
@RequestMapping("/device")
public class DeviceController {
    @Autowired
    IotService iotService;

    @Autowired
    IndexController indexController;

    @RequestMapping("/deleteDevice")
    public ModelAndView deleteDevice(ModelAndView modelAndView, String deviceName) {
        String str = iotService.deleteDevice(deviceName);
        return indexController.managepageDetail(modelAndView);
    }

    public ArrayList<Device> getDeviceList() {
        String devices = iotService.queryDevice();
        ArrayList<Device> deviceList = new ArrayList<>();

        JSONObject jsonObject = JSONArray.parseObject(devices);
        JSONArray data = (JSONArray) jsonObject.get("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj = data.getJSONObject(i);
            String productKey = (String) obj.get("productKey");
            String deviceName = (String) obj.get("deviceName");
            String nickname = (String) obj.get("nickname");
            deviceList.add(new Device(productKey, deviceName, nickname));
        }

        return deviceList;
    }

    @RequestMapping("/queryDevice")
    public ModelAndView queryDevice(ModelAndView modelAndView) {
        ArrayList<Device> deviceList = getDeviceList();
        modelAndView.addObject(deviceList);
        modelAndView.setViewName("managepageDetail");
        return modelAndView;
    }

    @RequestMapping("/registerDevice")
    public ModelAndView registerDevice(ModelAndView modelAndView, Device device) {
        String str = iotService.registerDevice(device.getDeviceName(), device.getRemarkName());
        return indexController.managepageDetail(modelAndView);
    }

}
